package portal.controller;

import beans.HttpConfig;
import net.sf.json.JSONObject;
import portal.dao.ScheduleJobDetailDao;
import utils.XmlUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;

import java.io.*;
import java.net.URLEncoder;
import java.util.List;


/**
 * Servlet implementation class GetTaskState
 */
public class GetJobXML extends BaseServlet {
    private static final long serialVersionUID = 1L;
    @Autowired
    ScheduleJobDetailDao scheduleJobDetailDao;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public GetJobXML() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String jobId = request.getParameter("jobId");
//        获取对应的作业详情
        
//        转换json到XML文件
        XmlUtil xmlUtil = new XmlUtil();
        JSONObject result = new JSONObject();
        List<Object> jobJson = scheduleJobDetailDao.getJobXMLJson(jobId);
        String jobJsonStr = null;
        if (jobJson.size() != 0){
            jobJsonStr = jobJson.get(0).toString();
        }
        response.setContentType("application/x-msdownload");
        String filePath = xmlUtil.saveJson2XML(jobId, jobJsonStr);
        File file = new File(filePath);
        //解决乱码问题
        String filename = URLEncoder.encode(file.getName(), "utf-8");
        //重置输出流
        response.reset();
        response.addHeader("Content-Disposition", "attachment;filename=" + filename);//设置文件名
        response.setContentType("application/octet-stream");//设置文件类型
        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());//获取二进制输出流
        //读取文件数据
        InputStream fis = new BufferedInputStream(new FileInputStream(filePath));
        byte[] buffer = new byte[4048];

        int size = 0;
        int len = 0;
        byte[] buf = new byte[1024];
        while ((size = fis.read(buf)) != -1) {
            len += size;
            toClient.write(buf, 0, size);
            // 打印下载百分比
//             System.out.println("下载了-------> " + len * 100 / fileLength + "%\n");
        }

        //    fis.read(buffer);
        fis.close();
        //输出文件数据
        toClient.flush();
        //     toClient.write(buffer);
        toClient.close();

    }
}